package demo;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MainApp {
    public static void main(String[] args) {
        ThreadLocal<String> tl = new ThreadLocal<>();
        InheritableThreadLocal itl = new InheritableThreadLocal();
        TransmittableThreadLocal<String> ttl1 = new TransmittableThreadLocal<>();
        TransmittableThreadLocal<String> ttl2 = new TransmittableThreadLocal<>();
        ExecutorService executor = Executors.newFixedThreadPool(1);
        executor.submit(() -> System.out.println("hello world"));

        tl.set("main-tl-1");
        itl.set("main-itl-1");
        ttl1.set("main-ttl1-1");
        ttl2.set("main-ttl2-1");
        // 提交第一个任务时, 就会在线程池里创建子线程
        executor.submit(TtlRunnable.get(() -> {
            tl.set("task1-tl");
            itl.set("task1-itl");
            ttl1.set("task1-ttl1");
            ttl1.set("task1-ttl2");
            System.out.println(Thread.currentThread().getName() + ": " + tl.get());
            System.out.println(Thread.currentThread().getName() + ": " + ttl1.get());
            System.out.println(Thread.currentThread().getName() + ": " + ttl2.get());
        }));


        tl.set("main-tl-2");
        itl.set("main-itl-2");
        ttl1.set("main-ttl1-2");
        ttl2.set("main-ttl2-2");
        // 需要把 runnable 包装成 ttlRunnable, 再提交给线程池, 才能包装 ttl 的值能传递给执行任务的线程
        executor.submit(TtlRunnable.get(() -> {
            tl.set("task2-tl");
            itl.set("task2-itl");
            ttl1.set("task2-ttl1");
            ttl1.set("task2-ttl2");
            System.out.println(Thread.currentThread().getName() + ": " + tl.get());
            System.out.println(Thread.currentThread().getName() + ": " + ttl1.get());
            System.out.println(Thread.currentThread().getName() + ": " + ttl2.get());
        }));

        executor.shutdown();
    }
}
